<template>
	<view class="question-item" :style="{ height: height ? height + 'px' : 'auto' }">
		<view class="question-content">
			<!--标题-->
			<view class="title-info">
				<rich-text :nodes="resetTitle(data)" class="title"></rich-text>
			</view>
			<!--问题描述-->
			<view class="rich-text" v-if="props.data.question && showHtml">
				<!--  <rich-text :nodes="data.question" v-if="data.question"></rich-text> -->
				<uvParse :domain="proxy.Api.domain" :content="props.data.question"></uvParse>
			</view>
			<!--问题选项-->
			<view class="question-option">
				<uv-checkbox-group 
				@change="handleCheck" 
				size="30" 
				placement="column" 
				v-model="checkBoxValue"
				v-if="props.data.questionType == 2"
				>
					<uv-checkbox shape="circle" :disabled="props.showAnswer" :customStyle="{margin: '7px'}"
						v-for="(item, index) in formateAnswerOptions(data)" :key="index" :label="item.text"
						:name="index">
						<template v-slot:default>
							<uvParse :content="item.text"></uvParse>
						</template>
					</uv-checkbox>
				</uv-checkbox-group>
				<uv-radio-group @change="handleRadio" size="30" placement="column" v-model="checkRadioValue"
					v-if="data.questionType == 0 || data.questionType == 1">
					<uv-radio :customStyle="{margin:'7px'}" :disabled="props.showAnswer"
						v-for="(item, index) in formateAnswerOptions(data)" :key="index" :label="item.text"
						:name="item.value">
						<template v-slot:default>
							<uvParse :content="item.text"></uvParse>
						</template>
					</uv-radio>
				</uv-radio-group>
<!-- 				<view v-if="props.data.questionType==2 && !props.showAnswer" class="checkBox-style">
					<button
						
						style="background: linear-gradient(to right, #9060df, #6356de);width: 120px;margin-top: 20px;border-radius: 15px;"
						class="mini-btn" type="primary" size="default" @click="handleCheckBox">
						{{showAnswer ? "下一题" : "确定"}}
					</button>
				</view> -->

			</view>
			<view class="custom-button" v-if="props.data.questionType == 3">
				<button
					style="background: linear-gradient(to right, #9060df, #6356de);width: 120px;margin-top: 20px;border-radius: 15px;"
					type="primary" size="default" @click="handleClick">{{buttonText}}</button>
			</view>
			<!--问题答案-->
			<view class="question-answer" v-if="props.showUserAnswer">
				<view class="left">
					<text>你的答案: </text>
					<text class="answer my" :style="{color: check() ? '#33CC33' : '#fb2e2e'}">{{
					  answer ? answer : "暂未作答"
					}}</text>
				</view>
				<view class="right">
					<text>参考答案: </text>
					<text class="answer">{{ getAnswer(data, 0) }}</text>
				</view>
			</view>
		</view>
		<template v-if="props.showAnswer || show">
			<!--分割线-->
			<view class="line"></view>
			<!--答案解析-->
			<view class="answer-analysis">
				<view class="title">- <text class="inner">试题详解</text> -</view>
				<view class="difficulty-panel">
					<view class="part-title">难度</view>
					<view class="star"><uni-rate size="20" :readonly="true" :value="data.difficultyLevel"
							activeColor="#aa6bd9" /></view>
				</view>
				<template v-if="props.showAnswer || show">
					<view class="part-title">题目解析</view>
					<view class="rich-text">
						<uvParse :domain="proxy.Api.domain" :content="props.data.answerAnalysis" v-if="props.data.answerAnalysis">
						</uvParse>
						<view class="no-data" v-if="!props.data.answerAnalysis">暂无答案解析</view>
					</view>
				</template>
			</view>
		</template>
		<view>
			<!-- 输入框示例 -->
			<uni-popup ref="inputDialog" type="dialog">
				<uni-popup-dialog mode="input" title="本题的自判分数" :value="answer" placeholder="请输入本题的分数"
					@confirm="dialogInputConfirm"></uni-popup-dialog>
			</uni-popup>
		</view>
	</view>
</template>

<script setup>
	import uvParse from "@/pages/components/uv-parse/components/uv-parse/uv-parse.vue";
	import {
		LETTER,
		QUESTION_TYPE,
		LOCAL_STORAGE_KEY
	} from "@/utils/Constants.js";
	import {
		ref,
		reactive,
		getCurrentInstance,
		nextTick,
		computed,
		watch
	} from "vue";
	import {
		onLoad,
		onUnload,
		onShow,
		
	} from "@dcloudio/uni-app";
	import {
		Checkbox
	} from "@dcloudio/uni-h5";
	const {
		proxy,
		ctx:that
	} = getCurrentInstance();
	onLoad(() => {
		nextTick(() => {
			if (props.cache != null) {
				const {
					userAnswer,
					questionType
				} = props.cache
				const arr = userAnswer.split(',')
				const res = []
				for (let i = 0; i < arr.length; i++) res.push(LETTER[arr[i]])
				answer.value = res.join("、")
				if (questionType == 2) {
					for (let i = 0; i < arr.length; i++) {
						checkBoxValue.value.push(parseInt(arr[i]))
					}
				} else checkRadioValue.value = userAnswer
			}
			if (props.userAnswer.length != 0) {
				let arr = props.userAnswer
				let res = []
				for (let i = 0; i < arr.length; i++) res.push(LETTER[arr[i]])
				answer.value = res.join("、")
				if (props.data.questionType == 2) {
					for (let i = 0; i < arr.length; i++) {
						checkBoxValue.value.push(parseInt(arr[i]))
					}
				} else checkRadioValue.value = props.data.userAnswer
			}
			that.$forceUpdate()
		})
	})
	// 修改事件定义，增加 autoSave 事件
	const emit = defineEmits(["changeAnswer", "autoSave"]);
	const props = defineProps({
		height: {
			type: Number,
		},
		data: {
			type: Object,
			default: {},
		},
		userAnswer: {
			type: Array,
			default: []
		},
		index: {
			type: Number,
		},
		cache: {
			type: Object
		},
		showAnswer: {
			type: Boolean,
			default: false,
		},
		showHtml: {
			type: Boolean,
			default: false,
		},
		showUserAnswer: {
			type: Boolean,
			default: false,
		},
	});
	const show = ref(false)
	const buttonText = ref("查看答案")
	const dialogInputConfirm = (val) => {
		inputDialog.value.close()
		answer.value = val
		let data = {
			questionId: props.data.questionId,
			userAnswer: answer.value,
			questionType: props.data.questionType
		}
		emit("changeAnswer", data)
		if (answer.value != "") {
			buttonText.value = "重新判分"
		}
	}
	const handleClick = () => {
		if (props.showAnswer) return
		if (buttonText.value == "查看答案") {
			buttonText.value = "判分"
			show.value = true
			return
		}
		emit("autoSave", props.data.questionId, answer.value)
		saveAnswerWithFallback(props.data.questionId, answer.value);
		inputDialog.value.open()
	}
	const style = {
		span: 'font-size: 40rpx'
	}
	
	const inputDialog = ref({})
	const checkBoxValue = ref([])
	const checkRadioValue = ref()
	const answer = ref("")
	const handleRadio = (val) => {
		let data = {
			questionId: props.data.questionId,
			userAnswer: val,
			questionType: props.data.questionType
		}
		emit("changeAnswer", data)
		// 自动保存
		emit('autoSave', props.data.questionId, val)
		if (props.data.questionType == 1) {
			answer.value = LETTER[val]
			return
		}
		answer.value = val == 1 ? "正确" : "错误"
		saveAnswerWithFallback(props.data.questionId, val);
	}
	
	// 添加本地缓存降级策略
	const localFallback = (questionId, answer) => {
	  const cache = uni.getStorageSync("exam_autosave") || {};
	  cache[questionId] = answer;
	  uni.setStorageSync("exam_autosave", cache);
	  console.warn("WebSocket 未连接，答案已本地缓存");
	};
	
	const handleCheck = () => {
		const answerResult = [];
		checkBoxValue.value.forEach(item => {
			answerResult.push(LETTER[item]);
		})
		answer.value = answerResult.join("、")
		let data = {
			questionId: props.data.questionId,
			userAnswer: checkBoxValue.value.join(","),
			questionType: props.data.questionType
		}
		emit("changeAnswer", data)
		// 触发自动保存（多选）
		emit("autoSave", props.data.questionId, checkBoxValue.value);
		saveAnswerWithFallback(props.data.questionId, checkBoxValue.value)
	}
	const handleCheckBox = () => {
		//如果已经显示答案
		// if (showAnswer.value == true) {
		// 	emits("nextPage")
		// 	return;
		// }
		handleCheck()
	}
	const resetTitle = (data) => {
		if (props.index) return (props.index + 1) + "." + data.title + "（" + QUESTION_TYPE[data.questionType] + "）";
		else return data.title + "（" + QUESTION_TYPE[data.questionType] + "）";
	};
	const check = () => {
		if (props.data.questionType == 2) return checkBoxValue.value.join(",") == props.data.questionAnswer
		return checkRadioValue.value == props.data.questionAnswer
	}

	const formateAnswerOptions = (question) => {
		let options = [];
		if (question.questionType == 0) {
			options = [{
					text: "正确",
					value: "1",
					disable: props.showAnswer,
				},
				{
					text: "错误",
					value: "0",
					disable: props.showAnswer,
				},
			];
			return options;
		}
		const questionItemList = question.questionItemList;
		for (let i = 0; i < questionItemList.length; i++) {
			options.push({
				text: questionItemList[i].title,
				value: i + "",
				disable: props.showAnswer,
			});
		}
		return options;
	};

	//获取正确答案
	const getAnswer = (item, answerType) => {
		if (item.questionAnswer == null) {
			return;
		}
		const answer = answerType == 0 ? item.questionAnswer : item.userAnswer;
		if (item.questionType == 0) {
			return answer == "0" ? "错误" : "正确";
		} else {
			const answerArray =
				answerType == 0 || (answerType == 1 && item.questionType !== 2) ?
				answer.split(",") :
				answer;
			const answerResult = [];
			answerArray.forEach((item) => {
				answerResult.push(LETTER[Number.parseInt(item)]);
			});
			return answerResult.join("、");
		}
	};
</script>

<style lang="scss" scoped>
	.question-item {
		overflow: auto;

		.question-content {
			padding: 10px;
			padding: 10px;

			:deep .uni-forms-item__label {
				display: none;
			}

			:deep .uni-forms-item {
				margin-bottom: 10px;
			}

			.title-info {
				align-items: top;
				line-height: 25px;

				.question-type {
					background: #0b93f4;
					color: #fff;
					font-weight: normal;
					padding: 1px 5px;
					border-radius: 3px;
					font-size: 13px;
				}

				.title {
					font-weight: bolder;
					display: inline;

					div {
						display: inline-block;
					}
				}

				.answer-result {
					width: 20px;
				}

				.iconfont {
					font-size: 30px;
				}

				.icon-ok {
					color: green;
				}

				.icon-wrong {
					color: red;
				}
			}

			.question-option {
				margin-top: 10px;
			}

			.question-answer {
				background: #efefef;
				padding: 5px 10px;
				font-weight: bold;
				border-radius: 3px;

				.answer {
					margin: 0px 15px 0px 5px;
					color: #33CC33;
				}

				.my {
					color: #fb2e2e;
					margin-left: 5px;
				}

				.iconfont {
					float: right;
					font-size: 20px;
					font-weight: normal;
				}

				.icon-ok {
					color: #07b107;
				}

				.icon-wrong {
					color: #fb2e2e;
				}
			}
		}

		.line {
			background: #ececec;
			height: 10px;
		}

		.answer-analysis {
			padding: 10px;
			overflow: auto;

			.title {
				text-align: center;
				color: #767575;
				margin: 5px 0px 10px;

				.inner {
					font-weight: bolder;
					color: #1f282e;
				}
			}

			.part-title {
				font-size: 16px;
				line-height: 30px;
				font-weight: bold;
				color: #3e3e3e;
			}

			.difficulty-panel {
				display: flex;
				align-items: center;
				margin-top: 5px;

				.star {
					flex: 1;
					margin-left: 5px;
				}
			}
		}

		.rich-text {
			padding: 5px 0px;
			font-size: 16px;
		}
	}
</style>